import { CommitUserColumns } from '@/pages/Admin/components/LeftTable';
import { listProductionLineUsingGET } from '@/services/model/productionLineController';
import {
  addRelationUsingPOST,
  deleteRelationUsingDELETE,
  listRelationByUserIdUsingGET,
} from '@/services/model/userProductionLineController';
import { useModel } from '@@/exports';
import { PlusOutlined } from '@ant-design/icons';
import type { ActionType, ProColumns } from '@ant-design/pro-components';
import { EditableProTable } from '@ant-design/pro-components';
import { Button, Form, message, Popconfirm, Select, Space } from 'antd';
import React, { useEffect, useRef, useState } from 'react';
import CustomSelect from "@/pages/components/CustomSelect";

type RightTableProps = {
  clickUser: undefined | CommitUserColumns;
};

const RightTable: React.FC<RightTableProps> = (props: RightTableProps) => {
  const { initialState } = useModel('@@initialState');
  const actionRef = useRef<ActionType>();
  const [editableKeys, setEditableRowKeys] = useState<React.Key[]>([]);
  const [dataSource, setDataSource] = useState<readonly API.RelationDTO[]>([]);
  const [productionLineList, setProductionLineList] = useState<readonly API.ProductionLineDTO[]>([],);
  const [selectValue, setSelectValue] = useState('');
  const [form] = Form.useForm();

  useEffect(() => {
    listProductionLineUsingGET({
      commitUserId: undefined,
    }).then((result) => {
      if (result.code === 0 && result.data) {
        setProductionLineList(result.data);
      }
    });
  }, []);

  useEffect(() => {
    actionRef.current?.reload();
  }, [props.clickUser?.id]);
  const initListRelation = async () => {
    if (props.clickUser?.id === undefined) {
      return {
        data: [],
      };
    }
    const result = await listRelationByUserIdUsingGET({
      commitUserId: props.clickUser?.id,
    });
    return {
      data: result.data,
    };
  };
  const CodeList = () => {
    return (
    <CustomSelect name={"产线编码"}
                  selectDate={selectValue}
                  setSelectData={setSelectValue}
                  datalist={productionLineList.map(item => {
                    return {id: item.code, name: item.code}
                  })}/>
    );
  };
  const NameList = () => {
    return (
    <CustomSelect name={"产线名称"}
                  selectDate={selectValue}
                  setSelectData={setSelectValue}
                  datalist={productionLineList.map(item => {
                    return {id: item.code, name: item.name}
                  })}/>
    );
  };

  const onDelete = async (id: number) => {
    const result = await deleteRelationUsingDELETE({
      id,
      currentUserId: initialState?.currentUser?.id,
    });
    if (result.code === 0 && result.data) {
      message.success('删除成功');
      actionRef.current?.reload();
    } else {
      message.error(result.message);
    }
  };
  const onSave = async () => {
    const currentUserId = initialState?.currentUser?.id;
    const newRelation: API.AddRelationQuery = {
      currentUserId,
      productionLineCode: selectValue,
      commitUserId: props.clickUser?.id,
    };
    const result = await addRelationUsingPOST(newRelation);
    if (result.code === 0 && result.data) {
      message.success('添加成功');
      actionRef.current?.reload();
    } else {
      message.error(result.message);
    }
    actionRef.current?.reload();
  };
  const columns: ProColumns<API.RelationDTO>[] = [
    {
      title: 'id',
      key: 'id',
      dataIndex: 'id',
      hideInTable: true,
      align: 'center',
    },
    {
      title: '编码',
      key: 'productionLineCode',
      dataIndex: 'productionLineCode',
      renderFormItem: () => {
        return <CodeList />;
      },
    },
    {
      title: '名称',
      key: 'productionLineName',
      dataIndex: 'productionLineName',
      renderFormItem: () => {
        return <NameList />;
      },
    },

    {
      title: '操作',
      valueType: 'option',
      render: (text, record) => [
        <Popconfirm
          key={'onDelete'}
          title="你想要删除这个关联吗"
          onConfirm={() => onDelete(record.id)}
          okText="Yes"
          cancelText="No"
        >
          <a key="deletable">删除</a>
        </Popconfirm>,
      ],
    },
  ];
  return (
    <>
      <Space style={{margin: "10px 10px 0px 10px"}}>
        <Button
          type="primary"
          onClick={() => {
            if (props.clickUser?.id === undefined) {
              message.warning("未选择要关联产线的用户")
              return;
            }
            setSelectValue('');
            actionRef.current?.addEditRecord?.({
              id: (Math.random() * 1000000).toFixed(0),
            });
          }}
          icon={<PlusOutlined />}
        >
          关联产线
        </Button>
      </Space>

      <EditableProTable<API.RelationDTO>
        rowKey="id"
        scroll={{y: 'calc(100vh - 205px)'}}
        actionRef={actionRef}
        headerTitle={'产线表（' + (props.clickUser?.name || '未选中用户') + '）'}
        // maxLength={5}
        // 关闭默认的新建按钮
        recordCreatorProps={false}
        columns={columns}
        request={() => initListRelation()}
        value={dataSource}
        onChange={setDataSource}
        editable={{
          form,
          editableKeys,
          onSave: async () => await onSave(),
          onChange: setEditableRowKeys,
          actionRender: (row, config, dom) => [dom.save, dom.cancel],
        }}
      />
    </>
  );
};

export default RightTable;
